package com.ice.utils;

import com.ice.common.domain.UserJwt;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by mrt on 2018/5/25.
 */
public class XcOauth2Util {

    public UserJwt getUserJwtFromHeader(HttpServletRequest request){
        Map<String, Object> jwtClaims = Oauth2Util.getJwtClaimsFromHeader(request);
        String id = String.valueOf(jwtClaims.get("id"));
        if(jwtClaims == null || StringUtils.isEmpty(id)){
            return null;
        }
        UserJwt userJwt = new UserJwt();
        userJwt.setId(id);
        userJwt.setName(String.valueOf(jwtClaims.get("name")));
        userJwt.setCompanyId(String.valueOf(jwtClaims.get("companyId")));
        userJwt.setUtype(String.valueOf(jwtClaims.get("utype")));
        userJwt.setUserpic(String.valueOf(jwtClaims.get("userpic")));
        return userJwt;
    }

    // obj.toString() 注意：必须保证Object不是null值，否则将抛出NullPointerException异常
    // 使用String.valueOf(Object)时，它会判断Object是否为空值，如果是，则返回null
    public static UserJwt getUserJwtFromHeaderTest(){
        String authorization = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55SWQiOiIxMjMiLCJ1c2VycGljIjpudWxsLCJ1c2VyX25hbWUiOiJpdGNhc3QiLCJzY29wZSI6WyJhcHAiXSwibmFtZSI6InRlc3QwMiIsInV0eXBlIjpudWxsLCJpZCI6NDksImV4cCI6MTU4NDI4MjEyMSwiYXV0aG9yaXRpZXMiOlsieGNfc3lzbWFuYWdlcl91c2VyIiwieGNfdGVhY2htYW5hZ2VyX2NvdXJzZV9saXN0IiwieGNfc3lzbWFuYWdlcl9yb2xlIiwieGNfdGVhY2htYW5hZ2VyX2NvdXJzZSIsImNvdXJzZV9maW5kX2xpc3QiLCJ4Y190ZWFjaG1hbmFnZXIiLCJ4Y19zeXNtYW5hZ2VyX21lbnUiXSwianRpIjoiODcxMDQzODEtN2NiZS00ZDBjLWJkMWItOGU0YThmNWJjYzBhIiwiY2xpZW50X2lkIjoiWGNXZWJBcHAifQ.BdauzL5GQnECdxiwopqzKg8Gi_weg8ozCiOgD-BlLKOUJUoe1D5tfmE-WuBUY-tAjljmPwu42YbliDBjsNOz8zyHBAowuU4zT1B65TqdP--DV_-9a5yDf6eeP_QEQyA44iEB0CO34nQtxLsm2nrbUeQuhujGlu_gdXLgKkcIm37zYnN_k7gdYS4SM0uIiivwSndBWAWXDrq7ty38bWArH-8c7CuOv0BWvsFQdu1W9e2E5gwaksBOZZasLZCBiGV4TV1uw39NG7o-wE0T5MleZGMmBubP3TnXF2OsY1Nj2i-NI9zZxwL9NN7n3oqC3h0raCjDUWtPFV7CNNWUr7KBQA";

        Map<String, Object> jwtClaims = Oauth2Util.getJwtClaimsFromHeaderTest(authorization);
        String id = String.valueOf(jwtClaims.get("id"));
        if(jwtClaims == null || StringUtils.isEmpty(id)){
            return null;
        }
        UserJwt userJwt = new UserJwt();
        userJwt.setId(id);
        userJwt.setName(String.valueOf(jwtClaims.get("name")));
        userJwt.setCompanyId(String.valueOf(jwtClaims.get("companyId")));
        userJwt.setUtype(String.valueOf(jwtClaims.get("utype")));
        userJwt.setUserpic(String.valueOf(jwtClaims.get("userpic")));
        return userJwt;
    }

    public static void main(String [] args){
        UserJwt u = getUserJwtFromHeaderTest();
    }

}
